package doc2db.interfaces.action;

import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;

/**
 *
 * @author yura
 */
public abstract class AbstractGUIAction implements GUIAction{
    private static GUIAction before = null;

    /**
     * Add curent gui action to list
     * @param action adding action
     * @return true if previous action ended
     */
    public static boolean init(GUIAction action){
        if (before == null){
            before = action;
        } else {
            boolean end = before.end();
            if (end){
                before = action;
            }
            return end;
        }
        return true;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (before == null){
            process(e);
        } else {
            boolean end = before.end();
            if (!end){
                error(" can finilized");
            } else {
                process(e);
            }
        }
    }

    private void process(ActionEvent e) {
        boolean start = start();
        if (start) {
            before = this;
            action(e);
        } else {
            error(" can start");
        }
    }

    private void error(String str){
        System.err.println(before.getClass().getName() + str);
        String msg = getMsg();
        if (msg != null) {
            try {
                JOptionPane.showMessageDialog(null, msg, "doc2db", JOptionPane.ERROR_MESSAGE);
            } catch (HeadlessException ex) {
                System.err.println(ex);
            }
        } else {
            System.err.println("\t reason not defineded!");
        }
    }

    @Override
    public boolean start(){
        return true;
    }

    @Override
    public boolean end() {
        return true;
    }

    @Override
    public abstract void action(ActionEvent e);

    @Override
    public String getMsg(){
        return null;
    }
}
